from channels.generic.websocket import AsyncWebsocketConsumer
from channels.exceptions import StopConsumer
import json
from datetime import datetime
from chat.models import Websocket
from asgiref.sync import sync_to_async

class ChatConsumer(AsyncWebsocketConsumer):
    async def websocket_connect(self, message):
        print("有人链接了")
        self.group_id = self.scope['url_route']['kwargs']['gid']
        self.uid = self.scope['url_route']['kwargs']['uid']
        self.gid_count = 0

        # Websocket
        await self.channel_layer.group_add(self.group_id, self.channel_name)
        # 接受客户连接
        await self.accept()

    async def websocket_receive(self, message):
        # Send message to room group
        print("websocket_receive-----message------------------------------>")
        print(message)

        # count：点击群聊时，更新人数
        # enter：websocket连接创建时，如果群聊里的人在聊天界面，就可以实时更新在线人数
        #       会被执行的场景：查询用户群聊数时、加入群聊时、创建群聊时
        #       对其他在这个群聊天界面的人，这时候如果有人加入聊天室，就可以实时更新在线人数
        if message['text'] == 'count' or message['text'] == 'enter':
            print('查询人数')
            self.gid_count = await self.get_guild_member_count(self.group_id)
            await self.channel_layer.group_send(self.group_id, {'type': 'online_user', 'message': {'gid_count': self.gid_count, 'gid': self.group_id, 'status': 'count', 'uid': self.uid}})
        # 在群聊中退出时，做两件事：
        # 1、对其他在这个群聊天界面的人 更新 在线群聊人数
        # 2、对其他在这个群聊天界面的人 显示 是谁退出了
        elif message['text'] == 'close':
            print('更新人数及显示谁退出了')
            self.gid_count = await self.get_guild_member_count(self.group_id) - 1
            await self.channel_layer.group_send(self.group_id, {'type': 'online_user_and_quit', 'message': {'gid_count': self.gid_count, 'gid': self.group_id, 'type': 'update', 'uid': self.uid}})
            await self.close()
        else:
            message['uid'] = str(self.uid)
            message['gid'] = str(self.group_id)
            await self.channel_layer.group_send(self.group_id, {'type': 'chat_message', 'message': message})

    async def websocket_disconnect(self, message):
        # 客户端主动断开连接时，触发
        print("断开连接")
        await self.channel_layer.group_discard(self.group_id, self.channel_name)
        raise StopConsumer()

    async def chat_message(self, event):
        message = event['message']
        time = str(datetime.now().time())
        message['time'] = time
        await self.send(text_data=json.dumps({"message": message}))
    
    async def online_user(self, event):  
        await self.send(text_data=json.dumps({"c_message": event['message']}))
    
    async def online_user_and_quit(self, event):  
        await self.send(text_data=json.dumps({"cq_message": event['message']}))

    @sync_to_async
    def get_guild_member_count(self, group_id):
        return Websocket.objects.filter(gid=group_id).first().member_count